//
//  ShopcartOrderViewController.m
//  B2C
//
//  Created by 李小龙 on 2017/8/10.
//  Copyright © 2017年 lixiaolong. All rights reserved.
//

#import "ShopcartOrderViewController.h"
#import "AddressChooseViewController.h"
#import "AddressChooserTableViewCell.h"
#import "OrderDetailTableViewCell.h"
#import <AlipaySDK/AlipaySDK.h>

#import "PayStatusViewController.h"

@interface ShopcartOrderViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>
{
    AddressChooserTableViewCell *_addressV;
}
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (weak, nonatomic) IBOutlet UIView *addressView;
@property (weak, nonatomic) IBOutlet UIButton *addressButton;
@property (weak, nonatomic) IBOutlet UIImageView *rightArrowImage;

@property (weak, nonatomic) IBOutlet UIButton *wechatButton;
@property (weak, nonatomic) IBOutlet UIButton *alipayButton;

@property (weak, nonatomic) IBOutlet UIButton *receiptButton;
@property (weak, nonatomic) IBOutlet UIButton *enterpriseButton;
@property (weak, nonatomic) IBOutlet UIButton *personalButton;
@property (weak, nonatomic) IBOutlet UIView *nameBackView;
@property (weak, nonatomic) IBOutlet UILabel *nameLabel;
@property (weak, nonatomic) IBOutlet UITextField *nameTextField;
@property (weak, nonatomic) IBOutlet UIView *numberBackView;
@property (weak, nonatomic) IBOutlet UITextField *numberTextField;
@property (weak, nonatomic) IBOutlet UIView *receiptTypeBackView;


@property (weak, nonatomic) IBOutlet UILabel *totalCountLabel;
@property (weak, nonatomic) IBOutlet UILabel *totalPriceLabel;

@property (nonatomic, copy) NSString *priceStr;
@property (nonatomic, copy) NSString *receiptType; // 0不开发票 1普通发票
@property (nonatomic, copy) NSString *receiptTitle;// 0个人 1企业

@end

@implementation ShopcartOrderViewController
#pragma mark - Get
- (NSMutableArray<ShopcartModel *> *)tableArray {
    if (!_tableArray) {
        _tableArray = [[NSMutableArray alloc] init];
    }
    return _tableArray;
}
#pragma mark - IBAction
- (IBAction)chooseAddressButtonAction:(id)sender {
    AddressChooseViewController *chooseVC = [[AddressChooseViewController alloc] init];
    chooseVC.selectModel = self.selectModel;
    chooseVC.isShopcartNew = YES;
    chooseVC.block = ^(AddressModel *chooseModel) {
        self.selectModel = chooseModel;
        [self updateUI];
    };
    [self.navigationController pushViewController:chooseVC animated:YES];
}
- (IBAction)wechatButtonAction:(id)sender {
    [self.wechatButton setSelected:YES];
    [self.alipayButton setSelected:NO];
}
- (IBAction)alipayButtonAction:(id)sender {
    [self.wechatButton setSelected:NO];
    [self.alipayButton setSelected:YES];
}
- (IBAction)submitButtonAction:(id)sender {
    
    if (!self.selectModel) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请选择收货地址" animated:YES];
        return;
    }
    if ([self.receiptType isEqualToString:@"1"]) {
        if (!TextIsNotNil(self.receiptTitle)) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请选择发票抬头" animated:YES];
            return;
        }
        if (!TextIsNotNil(self.nameTextField.text)) {
            [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请填写姓名" animated:YES];
            return;
        }
        if ([self.receiptTitle isEqualToString:@"1"]) {
            if (!TextIsNotNil(self.numberTextField.text)) {
                [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"请填写纳税人识别号" animated:YES];
                return;
            }
        }
    }
    
    NSString *payTypeStr = @"0";
    if (self.alipayButton.selected) {
//        [self uploadAlipay:self.priceStr];
        payTypeStr = @"1";
    } else {
//        [self uploadWechatPay:self.priceStr];
        payTypeStr = @"0";
    }
    
    // 提交订单
    [self uploadOrder:payTypeStr];
}

- (IBAction)receiptButtonAction:(id)sender {
    // 选择发票类型
    [self showAlertWithTitleArray:@[@"不开发票",@"普通发票",@"取消"] title:nil message:nil alertStyle:UIAlertControllerStyleActionSheet];
    __block typeof(self) blockSelf = self;
    self.alertBlock = ^(NSString *actionTitle) {
        if (![actionTitle isEqualToString:@"取消"]) {
            [blockSelf.receiptButton setTitle:actionTitle forState:UIControlStateNormal];
            if ([actionTitle isEqualToString:@"不开发票"]) {
                blockSelf.receiptType = @"0";
                [blockSelf.receiptTypeBackView setHidden:YES];
                [blockSelf.nameBackView setHidden:YES];
                [blockSelf.numberBackView setHidden:YES];
            }
            if ([actionTitle isEqualToString:@"普通发票"]) {
                blockSelf.receiptType = @"1";
                if (blockSelf.enterpriseButton.selected||(!blockSelf.enterpriseButton.selected && !blockSelf.personalButton.selected)) {
                    [blockSelf.numberBackView setHidden:NO];
                }
                [blockSelf.receiptTypeBackView setHidden:NO];
                [blockSelf.nameBackView setHidden:NO];
                
            }
        }
    };
}
- (IBAction)enterpriseButtonAction:(id)sender {
    // 企业
    self.receiptTitle = @"1";
    [self.nameLabel setText:@"添加名称："];
    [self.nameTextField setPlaceholder:@"请填写名称"];
    
    [self.enterpriseButton setSelected:YES];
    [self.personalButton setSelected:NO];
    
    [self.nameBackView setHidden:NO];
    [self.numberBackView setHidden:NO];
}
- (IBAction)personalButtonAction:(id)sender {
    // 个人
    self.receiptTitle = @"0";
    [self.nameLabel setText:@"添加姓名："];
    [self.nameTextField setPlaceholder:@"请填写姓名"];
    
    [self.enterpriseButton setSelected:NO];
    [self.personalButton setSelected:YES];
    
    [self.nameBackView setHidden:NO];
    [self.numberBackView setHidden:YES];
}

#pragma mark - UIViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"确认订单";
    self.selectModel = [UserInfo shareInstance].user.defaultAddress;
    self.receiptType = @"1";
    
    [self updateTableView];
    [self getPriceNetData];
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self updateUI];
}

- (void)keyboardWillShow:(NSNotification *)notification {
    [super keyboardWillShow:notification];
    if (self.nameTextField.isFirstResponder || self.numberTextField.isFirstResponder) {
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height-self.tableView.height+_keyboardEndFrame.size.height-55) animated:YES];
    }
}
- (void)keyboardWillHide:(NSNotification *)notification {
    [super keyboardWillHide:notification];
    if (self.tableView.contentSize.height < self.tableView.height) {
        [self.tableView setContentOffset:CGPointMake(0, 0) animated:YES];
    } else if ((self.tableView.contentOffset.y+self.tableView.height) > self.tableView.contentSize.height) {
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentSize.height-self.tableView.height) animated:YES];
    }
}

#pragma mark - 网络请求
- (void)uploadOrder:(NSString *)payType {
    NSString *scids = @"";
    for (NSInteger i = 0; i < self.tableArray.count; i++) {
        ShopcartModel *model = self.tableArray[i];
        if (i == 0) {
            scids = model.scid;
        } else {
            scids = [NSString stringWithFormat:@"%@,%@",scids,model.scid];
        }
    }
    
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    NSString *url = @"";
    if (TextIsNotNil(scids)) {
        [dic setObject:scids forKey:@"scids"];
        
        url = URL_Shopcart_Order;
    } else {
        [dic setObject:self.tableArray.firstObject.gaid forKey:@"gaid"];
        [dic setObject:self.tableArray.firstObject.number forKey:@"number"];
        
        url = URL_Goods_Order;
    }
    [dic setObject:self.selectModel.daid forKey:@"daid"];
    [dic setObject:payType forKey:@"ompaytype"];
    //发票
    [dic setObject:self.receiptType forKey:@"ominvoicetype"];
    if ([self.receiptType isEqualToString:@"1"]) {
        [dic setObject:self.receiptTitle forKey:@"ominvoicerise"];
        [dic setObject:self.nameTextField.text forKey:@"ominvoicename"];
        if ([self.receiptTitle isEqualToString:@"1"]) {
            [dic setObject:self.numberTextField.text forKey:@"ominvoicenumber"];
        } else {
            [dic setObject:@"" forKey:@"ominvoicenumber"];
        }
    } else {
        [dic setObject:@"" forKey:@"ominvoicerise"];
        [dic setObject:@"" forKey:@"ominvoicename"];
        [dic setObject:@"" forKey:@"ominvoicenumber"];
    }
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
//            //MARK:测试 根据类型跳支付宝、微信付款
//            self.omid = @"O51503991761";
//            
//            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
//            statusVC.omid = self.omid;
//            statusVC.type = StatusTypePaySuccess;
////            statusVC.type = StatusTypePayFail;
//            [self.navigationController pushViewController:statusVC animated:YES];
////            [self popToRootViewController];
//            return;
//            //MARK:-
            if (![responseObject[@"data"] isKindOfClass:[NSString class]]) {
                self.omid = responseObject[@"data"][@"omid"];
                
                if ([payType isEqualToString:@"1"]) {
                    [self uploadAlipay:responseObject[@"data"][@"url"]];
                } else if ([payType isEqualToString:@"0"]) {
                    [self uploadWechatPay:responseObject];
                }
            } else {
                [MBProgressHUD showError:self.view title:responseObject[@"data"] code:responseObject[@"code"] animated:YES];
            }
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
- (void)uploadAlipay:(NSString *)orderString {
    __weak typeof(self) weakSelf = self;
    // NOTE: 调用支付结果开始支付
    [[AlipaySDK defaultService] payOrder:orderString fromScheme:AppScheme callback:^(NSDictionary *resultDic) {
        NSLog(@"reslut = %@",resultDic);
        if ([resultDic[@"resultStatus"] isEqualToString:@"9000"]) {
            //成功
            if (weakSelf.block) {
                weakSelf.block(YES);
            } else {
                PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
                statusVC.omid = weakSelf.omid;
                statusVC.type = StatusTypePaySuccess;
                
                [weakSelf.navigationController pushViewController:statusVC animated:YES];
            }
        } else {
            //[MBProgressHUD myShowHUDAddedTo:weakSelf.view labelText:@"付款失败" animated:YES];
            PayStatusViewController *statusVC = [[PayStatusViewController alloc] init];
            statusVC.omid = weakSelf.omid;
            statusVC.type = StatusTypePayFail;
            
            [weakSelf.navigationController pushViewController:statusVC animated:YES];
        }
    }];
    
}
- (void)uploadWechatPay:(NSDictionary *)parameters {
    if (![WXApi isWXAppInstalled]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"没有安装微信" animated:YES];
        return;
    }
    if (![WXApi isWXAppSupportApi]) {
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"当前微信版本过低" animated:YES];
        return;
    }
    
    PayReq *request   = [[PayReq alloc] init];
    //request.openID    = responseObject[@"data"][@"appId"];
    request.partnerId = Wechat_partnerId;
    request.prepayId  = parameters[@"data"][@"prepayid"];
    request.package   = parameters[@"data"][@"package"];//Sign=WXPay
    request.nonceStr  = parameters[@"data"][@"noncestr"];
    request.timeStamp = [parameters[@"data"][@"timestamp"] unsignedIntValue];
    request.sign      = parameters[@"data"][@"sign"];
    if ([WXApi sendReq:request]) {
        NSLog(@"发送成功");
        if (self.block) {
            self.block(YES);
        }
    } else {
        NSLog(@"发送失败");
        [MBProgressHUD myShowHUDAddedTo:self.view labelText:@"订单获取失败" animated:YES];
    }
    
}
- (void)getPriceNetData {
    NSString *url;
    NSMutableDictionary *dic = [[NSMutableDictionary alloc] init];
    switch (self.type) {
        case ShopcartOrderTypeGoods:
        {
            url = URL_Goods_Settlement;
            [dic setObject:self.tableArray.firstObject.gaid forKey:@"gaid"];
            [dic setObject:self.tableArray.firstObject.number forKey:@"number"];
        } break;
        case ShopcartOrderTypeCart:
        {
            url = URL_Shopcart_Settlement;
            NSString *scids = @"";
            for (NSInteger i = 0; i < self.tableArray.count; i++) {
                ShopcartModel *tempModel = self.tableArray[i];
                if (i == 0) {
                    scids = tempModel.scid;
                } else {
                    scids = [NSString stringWithFormat:@"%@,%@",scids,tempModel.scid];
                }
            }
            [dic setObject:scids forKey:@"scids"];
        } break;
        default:
            break;
    }
    
    
    [MBProgressHUD showHUDProgress:self.view animated:YES];
    [MYAFNetworking POST:url parameters:dic success:^(NSURLSessionDataTask * _Nullable task, id  _Nullable responseObject) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if ([responseObject[@"code"] isEqualToString:@"200"]) {
            NSDictionary *netDic = responseObject[@"data"];
            self.priceStr = [NSString stringWithFormat:@"%.2f",[netDic[@"allprice"] floatValue]];
            [self updateUI];
        } else {
            [MBProgressHUD showError:self.view title:responseObject[@"message"] code:responseObject[@"code"] animated:YES];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nullable error) {
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        [MBProgressHUD showError:self.view title:@"" code:@"" animated:YES];
    }];
}
#pragma mark - action
- (void)updateTableView {
    [self.tableView clearExtendCellLine];
//    [self.tableView registerNib:[UINib nibWithNibName:@"OrderDetailTableViewCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"cellThird"];
}
- (void)updateUI {
    if (self.selectModel) {
        [self.addressButton setTitle:@"" forState:UIControlStateNormal];
        if (!_addressV) {
            _addressV = [[[NSBundle mainBundle] loadNibNamed:@"AddressChooserTableViewCell" owner:self options:nil] firstObject];
        }
        [_addressV setFrame:CGRectMake(0, 0, ScreenWidth-8-13, self.addressView.height)];
        // 选中按钮
        _addressV.selectBtnWLayout.constant = 0;
        [_addressV.selectButton setHidden:YES];
        // 收货人姓名
        [_addressV.nameLabel setText:self.selectModel.daname];
        // 手机号
        [_addressV.phoneLabel setText:[LXLIsPhoneNumber phoneNumber:self.selectModel.datel]];
        // 详细地址
        [_addressV.addressLabel setText:[NSString stringWithFormat:@"%@ %@ %@ %@",self.selectModel.pname,self.selectModel.cname,self.selectModel.aname,self.selectModel.daaddress]];
        // 是否默认
        if (!self.selectModel.isdefault) {
            _addressV.defaultWLayout.constant = 0;
        } else {
            _addressV.defaultWLayout.constant = 34.0;
        }
        
        [self.addressView insertSubview:_addressV.contentView belowSubview:self.addressButton];
        
        [_addressV layoutIfNeeded];
    } else {
        [self.addressButton setTitle:@"您还没有收货地址，点击这里去创建" forState:UIControlStateNormal];
        
//        [self.addressView removeFromSuperview];
    }
    
    [self.totalPriceLabel setText:self.priceStr];
    [self.totalCountLabel setText:[NSString stringWithFormat:@"共%ld件商品",self.tableArray.count]];
}
#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.tableArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    OrderDetailTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cellThird"];
    if (!cell) {
        cell = [[[NSBundle mainBundle] loadNibNamed:@"OrderDetailTableViewCell" owner:self options:nil] objectAtIndex:2];
    }
    ShopcartModel *model = self.tableArray[indexPath.row];
    
    [cell.thirdImageView sd_setImageWithURL:GetUrl(model.gimg) placeholderImage:PlaceholderImagePictures];
    [cell.thirdNameLabel setText:model.gname];
    [cell.thirdCountLabel setText:[NSString stringWithFormat:@"x%@",model.number]];
    [cell.thirdPriceLabel setText:[NSString stringWithFormat:@"¥%.2f",model.gaprice.floatValue]];
    // 属性
    GoodsAttributePriceModel *temp;
    for (GoodsAttributePriceModel *attModel in model.goodsattribute) {
        if ([model.gaid isEqualToString:attModel.gaid]) {
            temp = attModel;
            break;
        }
    }
    NSString *specs = @"";
    if (temp) {
        for (NSInteger i = 0; i < temp.twoattribute.count; i++) {
            TwoAtrributeModel *twoAtt = temp.twoattribute[i];
            if (i == 0) {
                specs = twoAtt.taname;
            } else {
                specs = [NSString stringWithFormat:@"%@;%@",specs,twoAtt.taname];
            }
        }
    }
    [cell.thirdSpecsLabel setText:specs];
    return cell;
}
#pragma mark - UITableViewDelegate

#pragma mark - UITextFieldDelegate
- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}
#pragma mark -
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
